<template>
  <div class="user-info-container">
    <!-- 头像和基本信息区域 -->
    <div class="profile-and-basic-info">
      <!-- 头像区域 -->
      <div class="profile-section">
        <el-card class="profile-card" style="width: 300px;height: 335px;">
          <div class="profile-content">
            <!-- 头像 -->
            <div class="avatar-section" @click="handleAvatarClick" title="点击修改头像">
              <img :src="avatarImg ? avatarImg : nullImageUrl" alt="Avatar" @error="handleImageError" class="avatar" />
            </div>
            <!-- 用户名 -->
            <div class="username-section">
              <h2>{{ displayUsername }}</h2>
            </div>
            <!-- 修改密码和退出登录按钮 -->
            <div class="action-buttons">
              <el-button type="primary" @click="handleModifyPassword">修改密码</el-button>
              <el-button type="primary" @click="logout">退出登录</el-button>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 基本信息栏 -->
      <div class="basic-info-section">
        <el-card class="basic-info-card" style="width: 500px;">
          <h3>基本信息</h3>
          <div class="divider"></div>
          <el-form label-width="80px">
            <el-form-item label="用户名">
              <el-input v-model="userInfo.username"></el-input>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="userInfo.phone"></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="userInfo.email"></el-input>
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="userInfo.gender">
                <el-radio value="男">男</el-radio>
                <el-radio value="女">女</el-radio>
                <el-radio value="保密">保密</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="modify-password-button" @click="submitForm">修改</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>

    <!-- 地址信息栏 -->
    <div class="address-info-section">
      <el-card class="address-info-card" style="width: 820px;">
        <h3>收货地址</h3>
        <div class="divider"></div>

        <el-collapse v-model="activeNames">
          <el-collapse-item v-for="(address, index) in userAddresses" :key="index" :name="index + 1">
            <template #title>
              地址{{ index + 1 }}
              <span v-if="address.isDefault" class="default-tag">默认地址</span>
            </template>
            <div class="address-item">
              <p><strong>收货人:</strong> {{ address.consignee }}</p>
              <p><strong>地址:</strong> {{ address.province }} {{ address.city }} {{ address.district }} {{ address.detail
              }}</p>
              <p><strong>电话:</strong> {{ address.phone }}</p>
              <div class="button-group">
                <el-button size="small" @click="editAddress(index)">修改</el-button>
                <el-button type="danger" size="small" @click="deleteAddress(address.addressId)">删除</el-button>
                <el-button v-if="!address.isDefault" type="primary" size="small"
                  @click="setDefaultAddress(address.addressId)">设为默认</el-button>
                <el-button v-else type="warning" size="small" @click="cancelDefaultAddress(address.addressId)">
                  取消默认
                </el-button>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>

        <el-button type="primary" class="add-address-button" @click="addAddress">添加地址</el-button>
      </el-card>
    </div>
  </div>

  <add-address-dialog v-model="addAddressDialog" @confirm="handleAddAddress" />
  <edit-address-dialog v-model="editAddressDialog" :current-edit-index="currentEditIndex"
    :current-address="currentAddress" @confirm="handleEditAddress" ref="editAddressDialogRef" />
  <edit-password-dialog v-model="dialogVisiblePassword" />
  <!-- @confirm="submitPasswordChange" -->
  <edit-avatar-dialog v-model="dialogVisibleAvatar" :current-avatar="avatarImg" @confirm="submitAvatar" />

</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import defaultAvatar from '@/assets/book2.jpg';
import AddAddressDialog from '@/components/user/addAddressDialog.vue';
import EditAddressDialog from '@/components/user/editAddressDialog.vue';
import EditPasswordDialog from '@/components/user/editPasswordDialog.vue';
import EditAvatarDialog from '@/components/user/editAvatarDialog.vue';
import { ElMessageBox, ElMessage, ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElOption } from 'element-plus';
import axios from 'axios';
axios.defaults.baseURL = "http://localhost:8080";
const router = useRouter(); // 使用 router
const addAddressDialog = ref(false);
const editAddressDialog = ref(false);
const editAddressDialogRef = ref();
const dialogVisiblePassword = ref(false)
const dialogVisibleAvatar = ref(false)
const displayUsername = ref('');
const userInfo = ref({
  username: '',
  phone: '', 
  email: '', 
  gender: '保密',
});

//头像加载失败的时候

// 使用 Vite 的 URL 解析方式处理静态资源
const defaultImageUrl = new URL('../../assets/error2.png', import.meta.url).href;
const nullImageUrl = new URL('../../assets/noPicture.jpg', import.meta.url).href;

// 处理图片加载失败事件
const handleImageError = (event) => {
  // 直接设置为默认图片
  event.target.src = defaultImageUrl;

  console.log('图片加载失败，已替换为默认图');
};

const activeNames = ref(['1']);
const genderMap = {
  0: '保密',
  1: '女',
  2: '男'
};
const avatarImg = ref();
//  获取用户信息
const fetchUserInfo = async () => {
  try {
    const token = sessionStorage.getItem('token'); // 获取本地存储的 token
    const response = await axios.get('/user/show', {
      headers: {
        Authorization: `${token}` // 添加 Token 到请求头 
      }
    }
    );
    if (response.data.code === 0) {
      const data = response.data.data;
      // 将数值性别转为文字
      data.gender = genderMap[data.gender] || '保密';
      displayUsername.value = data.username || '匿名用户'; // 设置默认值
      userInfo.value = data;
      avatarImg.value = data.avatar; // 如果 avatar 为空，则保持原值
    } else {
      ElMessage.error('获取用户信息失败');
    }
  } catch (error) {
    console.error('请求用户信息失败:', error);
    ElMessage.error('请求用户信息失败');
  }
};
//  修改用户信息
const submitForm = async () => {
  const reverseGenderMap = {
    '保密': 0,
    '女': 1,
    '男': 2
  };

  const payload = {
    ...userInfo.value,
    gender: reverseGenderMap[userInfo.value.gender]
  };

  try {
    const token = sessionStorage.getItem('token');
    const response = await axios.post('/user/updateUser', payload, {
      headers: {
        Authorization: `${token}` 
      }
    });
    if (response.data.code === 0) {
      ElMessage.success('更新成功');
      displayUsername.value = userInfo.value.username;
    } else {
      ElMessage.error(response.data.message);
      fetchUserInfo()
    }
  } catch (error) {
    console.error('更新用户信息失败:', error);
    ElMessage.error('更新用户信息失败');
  }
};

const userAddresses = ref([]);
//  获取用户地址列表
const fetchAddressList = async () => {
  try {
    const token = sessionStorage.getItem('token');
    const response = await axios.get('/address/list', {
      headers: {
        Authorization: `${token}`
      }
    });
    if (response.data.code === 0) {
      const addressList = response.data.data;
      console.log('Address list:', addressList);
      userAddresses.value = addressList.map(address => ({
        addressId: address.addressId,
        consignee: address.consignee,
        province: address.province,
        city: address.city,
        district: address.district,
        detail: address.detail,
        phone: address.phone,
        isDefault: address.isDefault
      }));
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    console.error('获取地址列表失败:', error);
    ElMessage.error('获取地址列表失败');
  }
};

const addAddress = () => {
  addAddressDialog.value = true;
};
//  添加地址列表
const handleAddAddress = async () => {
  await fetchAddressList(); // 刷新地址列表
};

const currentEditIndex = ref('');
const currentAddress = ref(null);
//将信息显示修改表单中到
const editAddress = (index) => {
  // const currentAddress = userAddresses.value[index];
  const address = userAddresses.value[index];

  if (!address || !address.addressId) {
    ElMessage.error('无效的地址信息');
    return;
  }
  // 设置当前编辑的地址 ID
  currentEditIndex.value = address.addressId;
  currentAddress.value = address;
  console.log('Current Address:', currentAddress.value);
  // 设置表单数据
  if (editAddressDialogRef.value) {
    editAddressDialogRef.value.addressForm = {
      consignee: currentAddress.consignee,
      province: currentAddress.province,
      city: currentAddress.city,
      district: currentAddress.district,
      detail: currentAddress.detail,
      phone: currentAddress.phone
    };
  }
  editAddressDialog.value = true;
};
// 编辑地址
const handleEditAddress = async () => {
  await fetchAddressList();
};

//  删除地址
const deleteAddress = async (addressId) => {
  try {
    await ElMessageBox.confirm('您确定要删除该地址吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const token = sessionStorage.getItem('token');
    const response = await axios.delete(`/address/delete/${addressId}`, {
      headers: {
        Authorization: `${token}`
      }
    });
    if (response.data.code === 0) {
      ElMessage.success('地址删除成功');
      // 第一次刷新数据
      await fetchAddressList();
    }else{
      ElMessage.error(response.data.message || '删除地址失败');
    }
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除');
    } else {
      console.error('删除地址失败:', error);
      ElMessage.error('删除地址失败');
    }
  }
};

//设置默认地址
const setDefaultAddress = async (addressId) => {
  try {
    const token = sessionStorage.getItem('token');
    const response = await axios.put(`/address/setDefault/${addressId}`, {}, {
      headers: {
        Authorization: `${token}`
      }
    });
    if (response.data.code === 0) {
      await fetchAddressList();
    } else {
      ElMessage.error(response.data.message || '设为默认地址失败');
    }
  } catch (error) {
    console.error('设为默认地址失败:', error);
    ElMessage.error('设为默认地址失败');
  }
};
//取消默认地址
const cancelDefaultAddress = async (addressId) => {
  try {
    const token = sessionStorage.getItem('token');
    const response = await axios.put(`/address/setUnDefault/${addressId}`, {}, {
      headers: {
        Authorization: `${token}`
      }
    });
    if (response.data.code === 0) {
      await fetchAddressList();
    } else {
      ElMessage.error(response.data.message || '取消默认地址失败');
    }
  } catch (error) {
    console.error('取消默认地址失败:', error);
    ElMessage.error('取消默认地址失败');
  }
};
const handleAvatarClick = () => {
  dialogVisibleAvatar.value = true
}

const submitAvatar = (url) => {
  avatarImg.value = url; // 更新头像显示
  ElMessage.success('头像上传成功');
};

//  修改密码
const handleModifyPassword = () => {
  dialogVisiblePassword.value = true
}
//  登出
const logout = async () => {
  try {
    // 添加确认对话框
    await ElMessageBox.confirm('您确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false // 禁止点击遮罩关闭
    });
    const response = await axios.get('/user/logout');

    if (response.data.code === 0) {
      // 注销成功，清除 token
      sessionStorage.removeItem('token');

      // 跳转到登录页面
      router.push('/login');
    } else {
      ElMessage.error(response.data.message || '退出失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退出失败:', error);
      ElMessage.error('退出失败');
    }
    // 如果用户点击取消，则不执行任何操作
  }
};

onMounted(() => {
  fetchUserInfo();
  fetchAddressList();
});

</script>

<style scoped>
.user-info-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.profile-and-basic-info {
  position: relative;
  /* 设置相对定位，作为绝对定位的参考 */
  width: 100%;
  max-width: 800px;
  margin-bottom: 30px;
}

.profile-section {
  position: absolute;
  /* 绝对定位，覆盖在基本信息栏上 */
  top: 0;
  left: 0;
  z-index: 1;
  /* 确保头像区域在上方 */
  text-align: center;
}

.avatar-section {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  border: 2px solid #409EFF;
  background-color: #fff;
  /* 白色背景防止透明图干扰 */
  /* padding: 8px; 内边距，让头像和边框之间有空隙 */
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  /* 可选：添加轻微阴影 */
  margin-bottom: 10px;
  margin-left: 65px;
}

.avatar-section:hover {
  cursor: pointer;
}

.avatar-section img {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
}

.username-section h2 {
  word-break: break-all;
  /* 强制文本换行 */
  white-space: normal;
  /* 允许文本自动换行 */
}

.username-section h3 {
  margin: 10px 0;
}

.action-buttons .el-button {
  margin: 40px 10px;
}

.basic-info-section {
  margin-left: 320px;
  /* 留出头像区域的空间 */
  z-index: 0;
  /* 确保在头像区域下方 */
}

.address-info-section {
  width: 100%;
  max-width: 800px;
}

.info-card {
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  background-color: #fff;
}

.divider {
  width: 100%;
  height: 1px;
  background-color: #4b90eb;
  margin: 10px 0;
}

.modify-password-button {
  margin-left: 120px;
}

.address-item {

  border: 1px solid #e4e7ed;
  /* 边框 */
  border-radius: 6px;
  /* 圆角 */
  background-color: #f9f9f9;
  /* 背景色（可选） */
}

.button-group {
  display: flex;
  margin-left: 580px;
  margin-bottom: 10px;
}

.add-address-button {
  margin-top: 20px;
  margin-left: 330px;
}

.default-tag {
  color: blue;
  font-weight: bold;
  margin-left: 10px;
}
</style>